package com.hyg.module_report.adapter;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.hyg.lib_base.MyView.BodyConstitutionPoint;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.WebView.WebViewActivity;
import com.hyg.module_report.R;
import com.hyg.module_report.model.ReportListData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


/*   自检页面的适配器   */
public class SelfReportAdapter extends RecyclerView.Adapter<SelfReportAdapter.ViewHolder> {
    private Context context;
    private ArrayList<ReportListData> dataList;
    private OnItemClickLitener mOnItemClickLitener;


    public SelfReportAdapter(Context activity, ArrayList<ReportListData> dataList) {
        this.context = activity;
        this.dataList = dataList;
    }

    public void addItem(ReportListData content, int position) {
        dataList.add(position, content);
        notifyItemInserted(position); //Attention!
    }

    public void removeItem(ReportListData model) {
        int position = dataList.indexOf(model);
        dataList.remove(position);
        notifyItemRemoved(position);//Attention!
    }


    public interface OnItemClickLitener {
        void onItemClick(View view, int position);
        void onItemLongClick(View view, int position);
    }

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_self_report,
                parent, false);
        ViewHolder holder = new ViewHolder(view);

//        holder.canteenName = (TextView) view.findViewById(R.id.canteenName);
//        holder.canteen = (ImageView) view.findViewById(R.id.canteen);

        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        ViewHolder viewHolder = (ViewHolder) holder;
        viewHolder.bindView(dataList.get(position), position);
    }

    public void removeData(int position) {
        dataList.remove(position);
        notifyItemRemoved(position);
    }

//    public long getItemId(int position) {
//        return position;
//    }

    @Override
    public int getItemCount() {
        if (dataList == null) {
            return 0;
        }
        return dataList.size();
    }

    //获取数据列表
    public ArrayList<BodyConstitutionPoint> newGetPoint(String BCPInfo) {
        ArrayList<BodyConstitutionPoint> _list = new ArrayList<BodyConstitutionPoint>();
        try {
            if (null != BCPInfo && !BCPInfo.equals("null") && !BCPInfo.equals("")) {
                JSONArray data = new JSONArray(BCPInfo);
                for (int i = 0; i < data.length(); i++) {
                    JSONObject body = new JSONObject(data.get(i).toString());
                    String name = body.getString("name");
                    String score = body.getString("score");
                    JSONArray result = new JSONArray(body.getString("result"));
                    BodyConstitutionPoint bcp = new BodyConstitutionPoint(
                            "" + name,
                            Double.parseDouble(score),
                            ScroeMeasureMethod(Double.parseDouble(score), result.length()),
                            "" + result.length(),
                            ""
                    );
                    _list.add(bcp);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return _list;
    }

    //计算体质得分方式
    public double ScroeMeasureMethod(double scroe, int itemNumber) {
        double changeScroe = ((scroe - itemNumber) * 100 / (itemNumber * 4));
        return changeScroe;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        //        private ReportListData item;
        private TextView report_physique;
        private TextView report_date;
        private UIHandler uiHandler;
        private String MainBody = "";
        private String secondaryBody = "";

        public Date stringToDate(String dateString) {
            //        ParsePosition position = new ParsePosition(0);
            if (null == dateString || dateString.equals("null") || dateString.equals("")) {
                Date date = new Date();
                return date;
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //        Date dateValue = simpleDateFormat.parse(dateString, position);
            Date dateValue = null;
            try {
                dateValue = simpleDateFormat.parse(dateString);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return dateValue;
        }

        public String dateToString(Date data, String formatType) {
            return new SimpleDateFormat(formatType).format(data);
        }

        public ViewHolder(View itemView) {
            super(itemView);
            uiHandler = new UIHandler();
            report_physique = (TextView) itemView.findViewById(R.id.report_physique);
            report_date = (TextView) itemView.findViewById(R.id.report_date);
        }

        public void bindView(final ReportListData data, final int pos) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    setPointsTitle(newGetPoint(data.getReport_hospital()));
                }
            }).start();
            Date temp = stringToDate(data.getReport_date().trim());
            report_date.setText(dateToString(temp, "yyyy年MM月dd日"));

            // 如果设置了回调，则设置点击事件
            if (mOnItemClickLitener != null) {
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Utils.isFastClick()) return;
                        int pos = getLayoutPosition();
                        mOnItemClickLitener.onItemClick(itemView, pos);
                        setjump();
                    }
                });

                itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int pos = getLayoutPosition();
                        mOnItemClickLitener.onItemLongClick(itemView, pos);
                        return false;
                    }
                });
            }
        }

        public void setjump() {
            if (!Utils.isEmpty(MainBody) && MainBody.length() >= 3) {
                String res = MainBody.substring(0, 3);
                Jump(res);
            } else {
                String res = secondaryBody.substring(0, 3);
                Jump(res);
//                context.overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        }

        public void Jump(String res) {
            Intent it = new Intent(context, WebViewActivity.class);
            if (res.equals("平和质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/pinghe.html");
            else if (res.equals("阳虚质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/yangxu.html");
            else if (res.equals("阴虚质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/yinxu.html");
            else if (res.equals("气虚质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/qixu.html");
            else if (res.equals("气郁质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/qiyu.html");
            else if (res.equals("湿热质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/shire.html");
            else if (res.equals("痰湿质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/tanshi.html");
            else if (res.equals("血瘀质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/xueyu.html");
            else if (res.equals("特禀质"))
                it.putExtra("url", "http://app.tcmhyg.com/med/tcm/tebing.html");
            else {
            }
            it.putExtra("title", res);
            context.startActivity(it);
        }

        public void setPointsTitle(List<BodyConstitutionPoint> Points) {
            Collections.sort(Points, new Comparator<BodyConstitutionPoint>() {
                public int compare(BodyConstitutionPoint bean1, BodyConstitutionPoint bean2) {
                    double i1 = bean1.getConversionScore();
                    double i2 = bean2.getConversionScore();
                    //降序排列
                    if (i1 > i2) {
                        return -1;
                    } else if (i1 < i2) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
            double maxvalue = 0.0;
            int maxpoint = 0;
            if (!Points.get(0).getBodyConstitutionTypes().equals("平和质")) {
                maxvalue = Points.get(0).getConversionScore();
                maxpoint = 0;
            } else {
                maxvalue = Points.get(1).getConversionScore();
                if (Points.get(0).getConversionScore() >= 60)
                    maxpoint = 1;
                else {
                    maxpoint = 2;
                }
            }//获取除了平和质的最大转化分
            MainBody = "";
            secondaryBody = "";
            for (int i = 0; i < Points.size(); i++) {
                double Pointdatas = Points.get(i).getConversionScore();
                String name = Points.get(i).getBodyConstitutionTypes();
                if (Pointdatas >= 30)
                    if (name.equals("平和质")) {
                        if (maxvalue < 40 && Pointdatas >= 60) {
                            MainBody += Points.get(i).getBodyConstitutionTypes() + "、";
                        }
                    } else {
                        if (maxvalue >= 40 && Pointdatas >= 40) {
                            MainBody += Points.get(i).getBodyConstitutionTypes() + "、";

                        } else if (maxvalue >= 40 && Pointdatas < 40 && Pointdatas >= 30) {
                            secondaryBody += Points.get(i).getBodyConstitutionTypes() + "、";

                        } else if (maxvalue < 40 && Pointdatas < 40 && Pointdatas >= 30 && maxpoint == 2) {
                            secondaryBody += Points.get(i).getBodyConstitutionTypes() + "、";

                        } else if (maxvalue < 40 && Pointdatas >= 30 && maxpoint == 1) {
                            secondaryBody += Points.get(i).getBodyConstitutionTypes() + "、";

                        }
                    }
            }
            if (!Utils.isEmpty(MainBody)) {
                Message msg = new Message();
                msg.obj = MainBody;
                msg.what = 1;
                uiHandler.sendMessage(msg);
            } else {
                Message msg = new Message();
                msg.obj = secondaryBody;
                msg.what = 1;
                uiHandler.sendMessage(msg);
            }

        }

        public class UIHandler extends Handler {
            //自定义handler用来接收从服务器端返回的包装数据
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1://个人信息已保存
                        if (!Utils.isEmpty(msg.obj.toString())) {
                            report_physique.setText("检测结果：" + msg.obj.toString().substring(0, msg.obj.toString().length() - 1) + "。");
                        } else {
//                            report_physique.setText("检测结果：" + msg.obj.toString().substring(0, msg.obj.toString().length() - 1) + "。");
                        }
                        break;
                }
            }
        }
    }
}